﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
using Loki.Utils;

namespace Loki.Model
{
    /// <summary>
    /// Entity primary key mapper.
    /// </summary>
    /// <typeparam name="TEntityClass">Entity class type.</typeparam>
    /// <typeparam name="TEntityKey">Entity key type.</typeparam>
    public class UniqueKeyMapper<TEntityClass, TEntityKey> : LokiObject, IDisposable, IKeyMapper<TEntityClass>, IEnumerable<TEntityClass>
    {
        #region Constructors

        public UniqueKeyMapper(Expression<Func<TEntityClass, TEntityKey>> P_Indexer, IEqualityComparer<TEntityKey> P_Comparer)
        {
            if (P_Comparer != null)
            {
                _Store = new ConcurrentDictionary<TEntityKey, TEntityClass>(P_Comparer);
            }
            else
            {
                _Store = new ConcurrentDictionary<TEntityKey, TEntityClass>();
            }

            _Indexer = P_Indexer.Compile();
        }
        #endregion

        #region Fields

        private Func<TEntityClass, TEntityKey> _Indexer;
        private ConcurrentDictionary<TEntityKey, TEntityClass> _Store;

        #endregion

        #region Load & Reset

        /// <summary>
        /// Resets the mapper.
        /// </summary>
        public void Reset()
        {
            _Store.Clear();
        }

        /// <summary>
        /// Determines whether the specified key is loaded in mapper.
        /// </summary>
        /// <param name="P_Key">The key.</param>
        /// <returns>
        ///  <c>true</c> if the specified key is loaded; otherwise, <c>false</c>.
        /// </returns>
        public bool IsLoaded(object P_Key)
        {
            return _Store.ContainsKey((TEntityKey)P_Key);
        }

        public void MarkAsLoaded(object P_Key)
        {
            // do nothing
        }

        #endregion

        #region Getters
        /// <summary>
        /// Computes the index.
        /// </summary>
        /// <param name="P_Entity">The entity.</param>
        /// <returns></returns>
        public object ComputeIndex(TEntityClass P_Entity)
        {
            return _Indexer(P_Entity);
        }

        /// <summary>
        /// Gets the entity for the specified key.
        /// </summary>
        /// <param name="P_Key">The key.</param>
        /// <returns></returns>
        public TEntityClass Get(TEntityKey P_Key)
        {
            TEntityClass L_Buffer = default(TEntityClass);

            _Store.TryGetValue(P_Key, out L_Buffer);

            return L_Buffer;
        }

        /// <summary>
        /// Gets the entities corresponding to the specified value.
        /// </summary>
        /// <param name="P_Key">The key.</param>
        /// <returns></returns>
        public IEnumerable<TEntityClass> GetAllByKey(object P_Key)
        {
            List<TEntityClass> L_Return = new List<TEntityClass>();

            TEntityClass L_Item = Get((TEntityKey)P_Key);

            if (!object.Equals(L_Item, default(TEntityClass)))
            {
                L_Return.Add(L_Item);
            }

            return L_Return;
        }

        #endregion

        #region Registering & Unregistering
        /// <summary>
        /// Registers an entity into mapper.
        /// </summary>
        /// <param name="P_Entity"></param>
        private bool _Register(TEntityClass P_Entity)
        {
            TEntityKey L_EntityHash = _Indexer(P_Entity);
            bool L_Return = !_Store.ContainsKey(L_EntityHash);
            _Store[L_EntityHash] = P_Entity;

            return L_Return;
        }

        public bool Register(TEntityClass P_Entity)
        {
            TEntityKey L_EntityHash = _Indexer(P_Entity);
            bool L_Return = true;
            _Store.AddOrUpdate(L_EntityHash, P_Entity, (k, v) => { L_Return = false; return P_Entity; });
            return L_Return;
        }

        public void Remove(TEntityClass P_Entity)
        {
            TEntityKey L_EntityHash = _Indexer(P_Entity);
            TEntityClass L_Value = default(TEntityClass);
            _Store.TryRemove(L_EntityHash, out L_Value);
        }
        #endregion

        #region IDisposable
        /// <summary>
        /// Releases all resources used by an instance of the <see cref="UniqueKeyMapper" /> class.
        /// </summary>
        /// <remarks>
        /// This method calls the virtual <see cref="Dispose(bool)" /> method, passing in <strong>true</strong>, and then suppresses 
        /// finalization of the instance.
        /// </remarks>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged resources before an instance of the <see cref="UniqueKeyMapper" /> class is reclaimed by garbage collection.
        /// </summary>
        /// <remarks>
        /// This method releases unmanaged resources by calling the virtual <see cref="Dispose(bool)" /> method, passing in <strong>false</strong>.
        /// </remarks>
        ~UniqueKeyMapper()
        {
            Dispose(false);
        }

        /// <summary>
        /// Releases the unmanaged resources used by an instance of the <see cref="UniqueKeyMapper" /> class and optionally releases the managed resources.
        /// </summary>
        /// <param name="P_Disposing">Set to <strong>true</strong> to release both managed and unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool P_Disposing)
        {
            if (P_Disposing)
            {
                _Store.Clear();
            }
        }
        #endregion

        #region IEnumerable
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<TEntityClass> GetEnumerator()
        {
            foreach (TEntityClass L_Item in _Store.Values)
            {
                if (!object.Equals(L_Item, default(TEntityClass)))
                {
                    yield return L_Item;
                }
            }
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion
    }
}
